//
//  KTitlesSelectedView.m
//  NeiHan
//
//  Created by Kevin on 2017/3/20.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KTitlesSelectedView.h"
#import "KTitleItem.h"

#define ItemWidth kScreenWidth/6.0

@interface KTitlesSelectedView ()<UIScrollViewDelegate>

@property(nonatomic,weak)UIScrollView* scrollView;

@end

@implementation KTitlesSelectedView

-(instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        
    }
    return self;
}

-(void)setSelectedIndex:(NSInteger)selectedIndex{
    _selectedIndex = selectedIndex;
    
    for (KTitleItem* item in self.scrollView.subviews) {
        if ([item isKindOfClass:[KTitleItem class]]) {
            if (item.selected) {
                item.selected = NO;
            }
        }
    }
    
    KTitleItem* currentItem = [self.scrollView viewWithTag:selectedIndex+1];
    if ([currentItem isKindOfClass:[KTitleItem class]]) {
        currentItem.selected = YES;
    }
}

-(void)setTitles:(NSArray *)titles{
    if (!titles || titles.count == 0) return;
    CGFloat Width = self.frame.size.width/titles.count;
    self.scrollView.contentSize = CGSizeMake(Width*titles.count, 0);
    @weakify(self);
    for (NSInteger i = 0; i < titles.count; i++) {
        KTitleItem* item = [self cItem];
        item.tag = i+1;
        item.selectColor = [UIColor colorWithRed:254/255.0 green:118/255.0 blue:77/255.0 alpha:1.00f];
        item.normalColor = [UIColor darkGrayColor];
        item.frame = CGRectMake(i*Width, 0, Width, self.height);
        [item setTitle:titles[i]];
        item.frame = CGRectMake(i*Width, 0, Width, self.height);
        item.selected = NO;
        if (0 == i) {
            item.selected = YES;
        }
        
        item.ClickTitle = ^(){
            [weak_self itemsClick:i];
        };
    }
    self.selectedIndex = 0;
}

-(KTitleItem*)cItem{
    KTitleItem* item = [[KTitleItem alloc]init];
    item.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:item];
    return item;
}

-(UIScrollView *)scrollView{
    if (!_scrollView) {
        UIScrollView* scrl = [[UIScrollView alloc]initWithFrame:self.bounds];
        scrl.delegate = self;
        scrl.backgroundColor = [UIColor clearColor];
        [self addSubview:scrl];
        _scrollView = scrl;
    }
    return _scrollView;
}

-(void)itemsClick:(NSInteger)index{
    
    if (self.itemClickBlock) {
        self.itemClickBlock(index);
    }
    self.selectedIndex = index;
}

@end
